/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package boundary;

import components.POwnerDisplay;
import components.POwnerRegistration;
import components.POwnerUpdate;
import components.PPetDisplay;
import components.PPetRegistration;
import components.PPetUpdate;
import components.PSearchResults;
import components.PVetDisplay;
import components.PVetRegistration;
import components.PVetUpdate;
import dao.OwnerDAO;
import dao.PersonDAO;
import dao.PetDAO;
import dao.VeterinarianDAO;
import entity.Owner;
import entity.Pet;
import entity.Veterinarian;
import hpvas.HPVAS;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import javax.persistence.Persistence;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author Juan
 */
public class MainWindow extends javax.swing.JFrame {

    /**
     * Creates new form MainWindow
     */
    public MainWindow() {
        initComponents();
        setLocationRelativeTo(null);
        jScrollPane1.getVerticalScrollBar().setUnitIncrement(30);
        jScrollPane2.getVerticalScrollBar().setUnitIncrement(30);
    }
    
    public void closeCurrentTab() {
        int selectedIndex = TPMainPane.getSelectedIndex();
        if (selectedIndex != -1) {
            Component selectedComponent = TPMainPane.getSelectedComponent();
            if (selectedComponent instanceof PVetDisplay) {
                PVetDisplay pvd = (PVetDisplay) selectedComponent;
                pvd.save();
            } else if (selectedComponent instanceof PPetDisplay) {
                PPetDisplay ppd = (PPetDisplay) selectedComponent;
                ppd.save();
            }
            TPMainPane.remove(selectedIndex);
        }
    }
    
    private void updateTreeItem(int nodeIndex, List objects) {
        //nodeIndex is the node where the objects should be inserted.
        DefaultTreeModel model = (DefaultTreeModel) TMainTree.getModel();
        DefaultMutableTreeNode updatedNode = (DefaultMutableTreeNode) model.getChild(model.getRoot(), nodeIndex);
        
        TreePath updateNodePath = new TreePath(model.getPathToRoot(updatedNode));
        boolean collapsed = TMainTree.isCollapsed(updateNodePath);
        updatedNode.removeAllChildren();
        model.reload();
        
        //Tree Set used to order the objects alphabetically.
        TreeSet<Owner> orderedObjects = new TreeSet<>(new Comparator() {

            @Override
            public int compare(Object o1, Object o2) {
                return o1.toString().compareToIgnoreCase(o2.toString());
            }
        });
        orderedObjects.addAll(objects);
        
        for (Object object : orderedObjects) {
            model.insertNodeInto(new DefaultMutableTreeNode(object), updatedNode, updatedNode.getChildCount());
        }
        
        if (!collapsed) {
            TMainTree.expandPath(updateNodePath);
        }
    }
    
    public void updatePets(List<Pet> pets) {
        updateTreeItem(0, pets);
    }
    
    public void updateOwners(List<Owner> owners) {
        updateTreeItem(1,owners);
    }
    
    public void updateVeterinarians(List<Veterinarian> veterinarians) {
        updateTreeItem(2, veterinarians);
    }
    
    private boolean showPopup(DefaultMutableTreeNode clickedNode, MouseEvent e) {
        DefaultTreeModel model = (DefaultTreeModel) TMainTree.getModel();
        TreePath treePath = new TreePath(model.getPathToRoot(clickedNode));
        TMainTree.expandPath(treePath);
        TMainTree.setSelectionPath(treePath);
        
        if (e.isPopupTrigger()) {
            switch (clickedNode.getUserObject().getClass().getSimpleName()) {
                case "Veterinarian":
                    MIEditEntity.setText("Edit veterinarian");
                    MIDeleteEntity.setText("Delete veterinarian");
                    break;
                    
                case "Owner":
                    MIEditEntity.setText("Edit owner");
                    MIDeleteEntity.setText("Delete owner");
                    break;
                    
                case "Pet":
                    MIEditEntity.setText("Edit pet");
                    MIDeleteEntity.setText("Delete pet");
                    break;
                    
                case "String":
                    return false;
                    
                default:
            }
            PMTreePopupMenu.show(e.getComponent(), e.getX(), e.getY());
            return true;
        }
        
        return false;
    }
    
    private Object getSelectedEntity() {
        Object userObject = null;
        TreePath selectionPath = TMainTree.getSelectionPath();
        if (selectionPath != null) {
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
            userObject = selectedNode.getUserObject();
        }
        return userObject;
    }
    
    private void editSelectedEntity() {
        Object userObject = getSelectedEntity();
        if (userObject != null) {
            if (alreadyOpen(userObject.toString())) {
                closeCurrentTab();
            }
            if (userObject instanceof Owner) {
                openPanel("Edit " + userObject.toString(), new POwnerUpdate((Owner) userObject));
            } else if (userObject instanceof Veterinarian) {
                openPanel("Edit " + userObject.toString(), new PVetUpdate((Veterinarian) userObject));
            } else if (userObject instanceof Pet) {
                openPanel("Edit " + userObject.toString(), new PPetUpdate((Pet) userObject));
            }
        }
    }
    
    public void editEntity(Object entity) {
        if (alreadyOpen(entity.toString())) {
                closeCurrentTab();
        }
        if (entity instanceof Owner) {
                openPanel("Edit " + entity.toString(), new POwnerUpdate((Owner) entity));
            } else if (entity instanceof Veterinarian) {
                openPanel("Edit " + entity.toString(), new PVetUpdate((Veterinarian) entity));
            } else if (entity instanceof Pet) {
                openPanel("Edit " + entity.toString(), new PPetUpdate((Pet) entity));
        }
    }
    
    public void displayEntity(Object entity) {
        if (!alreadyOpen("Edit " + entity)) {
            if (entity instanceof Owner) {
                openPanel(entity.toString(), new POwnerDisplay((Owner) entity));
            } else if (entity instanceof Veterinarian) {
                openPanel(entity.toString(), new PVetDisplay((Veterinarian) entity));
            } else if (entity instanceof Pet) {
                openPanel(entity.toString(), new PPetDisplay((Pet) entity));
            }
        }
    }
    
    public boolean alreadyOpen(String tabName) {
        boolean alreadyOpen = false;
        for (int i = 0; i < TPMainPane.getTabCount(); i++) {
            if (TPMainPane.getTitleAt(i).equals(tabName)) {
                System.out.println(TPMainPane.getTitleAt(i)+" "+tabName);
                alreadyOpen = true;
                TPMainPane.setSelectedIndex(i);
                break;
            }
        }
        return alreadyOpen;
    }
    
    private void openPanel(String title, Component component) {
        if (!alreadyOpen(title)) {
            TPMainPane.add(title, component);
            TPMainPane.setSelectedIndex(TPMainPane.getTabCount() - 1);
        }
    }
    
    public void deleteEntity(Object entity) {
        String className = entity.getClass().getSimpleName().toLowerCase();
        int choice = JOptionPane.showConfirmDialog(this,
                                        "Are you sure you want to remove the " + className + " " + entity + "?",
                                        "Confirm Removal",
                                        JOptionPane.YES_NO_OPTION,
                                        JOptionPane.WARNING_MESSAGE);
        
        if (choice == JOptionPane.YES_OPTION) {
            if (entity instanceof Owner) {
                try {
                    OwnerDAO ownerDAO = new OwnerDAO(Persistence.createEntityManagerFactory("HPVA"));
                    ownerDAO.destroy((Owner) entity);
                    HPVAS.loadOwners();
                    HPVAS.loadPets();
                    JOptionPane.showMessageDialog(this,
                            entity + " was removed correctly.","Info", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this,
                            "There was an error deleting the object.", "Error", JOptionPane.ERROR_MESSAGE);
                    System.err.println(e.getMessage());
                }
            } else if (entity instanceof Veterinarian) {
                try {
                    VeterinarianDAO veterinarianDAO = new VeterinarianDAO(Persistence.createEntityManagerFactory("HPVA"));
                    veterinarianDAO.destroy((Veterinarian) entity);
                    HPVAS.loadPets();
                    HPVAS.loadVeterinarians();
                    JOptionPane.showMessageDialog(this,
                            entity + " was removed correctly.","Info", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this,
                            "There was an error deleting the object.", "Error", JOptionPane.ERROR_MESSAGE);
                    System.err.println(e.getMessage());
                }
            } else if (entity instanceof Pet) {
                try {
                    PetDAO petDAO = new PetDAO(Persistence.createEntityManagerFactory("HPVA"));
                    petDAO.destroy((Pet) entity);HPVAS.loadPets();
                    HPVAS.loadVeterinarians();
                    JOptionPane.showMessageDialog(this,
                            entity + " was removed correctly.","Info", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this,
                            "There was an error deleting the object.", "Error", JOptionPane.ERROR_MESSAGE);
                    System.err.println(e.getMessage());
                }
            }
            if (alreadyOpen(entity.toString()) || alreadyOpen("Edit " + entity.toString())) {
                closeCurrentTab();
            }
        }
    }
    
    private void search() {
        if (CBSearch.getSelectedIndex() != 0) {
            String query = TFSearch.getText();
            if (query != null && !query.equals("Enter your search here...")) {
                query = query.trim();
                String[] queryWords = query.split(" ");
                VeterinarianDAO veterinarianDAO = new VeterinarianDAO(Persistence.createEntityManagerFactory("HPVA"));
                PetDAO petDAO = new PetDAO(Persistence.createEntityManagerFactory("HPVA"));
                OwnerDAO ownerDAO = new OwnerDAO(Persistence.createEntityManagerFactory("HPVA"));
                PersonDAO personDAO = new PersonDAO(Persistence.createEntityManagerFactory("HPVA"));
                
                switch (CBSearch.getSelectedIndex()) {
                    case 1:
                        TPMainPane.add("Search by " + CBSearch.getSelectedItem(),
                                new PSearchResults(queryWords, (String) CBSearch.getSelectedItem(), veterinarianDAO.findByName(queryWords)));
                        TPMainPane.setSelectedIndex(TPMainPane.getTabCount() - 1);
                        break;
                        
                    case 2:
                        TPMainPane.add("Search by " + CBSearch.getSelectedItem(),
                                new PSearchResults(queryWords, (String) CBSearch.getSelectedItem(), petDAO.findByName(queryWords)));
                        TPMainPane.setSelectedIndex(TPMainPane.getTabCount() - 1);
                        break;
                        
                    case 3:
                        TPMainPane.add("Search by " + CBSearch.getSelectedItem(),
                                new PSearchResults(queryWords, (String) CBSearch.getSelectedItem(), ownerDAO.findByName(queryWords)));
                        TPMainPane.setSelectedIndex(TPMainPane.getTabCount() - 1);
                        break;
                        
                    case 4:
                        TPMainPane.add("Search by " + CBSearch.getSelectedItem(),
                                new PSearchResults(queryWords, (String) CBSearch.getSelectedItem(), personDAO.findBySSN(queryWords)));
                        TPMainPane.setSelectedIndex(TPMainPane.getTabCount() - 1);
                        break;
                        
                    case 5:
                        List entities = ownerDAO.findByName(queryWords);
                        entities.addAll(petDAO.findByName(queryWords));
                        entities.addAll(veterinarianDAO.findByName(queryWords));
                        TPMainPane.add("Search by " + CBSearch.getSelectedItem(),
                                new PSearchResults(queryWords, (String) CBSearch.getSelectedItem(), entities));
                        TPMainPane.setSelectedIndex(TPMainPane.getTabCount() - 1);
                        
                    default:
                }
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PMTreePopupMenu = new javax.swing.JPopupMenu();
        MIViewEntity = new javax.swing.JMenuItem();
        MIEditEntity = new javax.swing.JMenuItem();
        MIDeleteEntity = new javax.swing.JMenuItem();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        TMainTree = new javax.swing.JTree();
        jScrollPane2 = new javax.swing.JScrollPane();
        TPMainPane = new javax.swing.JTabbedPane();
        jLabel1 = new javax.swing.JLabel();
        TFSearch = new javax.swing.JTextField();
        CBSearch = new javax.swing.JComboBox();
        menuBar = new javax.swing.JMenuBar();
        MActionsMenu = new javax.swing.JMenu();
        MIRegisterOwner = new javax.swing.JMenuItem();
        MIRegisterPet = new javax.swing.JMenuItem();
        MIRegisterVet = new javax.swing.JMenuItem();
        MIExit = new javax.swing.JMenuItem();
        MEditMenu = new javax.swing.JMenu();
        MIEditSelected = new javax.swing.JMenuItem();
        MTabsMenu = new javax.swing.JMenu();
        MICloseCurrentTab = new javax.swing.JMenuItem();
        MHelpMenu = new javax.swing.JMenu();
        MIAbout = new javax.swing.JMenuItem();

        MIViewEntity.setText("View data");
        MIViewEntity.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIViewEntityActionPerformed(evt);
            }
        });
        PMTreePopupMenu.add(MIViewEntity);

        MIEditEntity.setText("jMenuItem1");
        MIEditEntity.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIEditEntityActionPerformed(evt);
            }
        });
        PMTreePopupMenu.add(MIEditEntity);

        MIDeleteEntity.setText("jMenuItem1");
        MIDeleteEntity.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIDeleteEntityActionPerformed(evt);
            }
        });
        PMTreePopupMenu.add(MIDeleteEntity);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Healthy Pets Association System");
        setMinimumSize(new java.awt.Dimension(350, 500));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jSplitPane1.setDividerLocation(200);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("HPVA");
        javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Pets");
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Owners");
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Veterinarians");
        treeNode1.add(treeNode2);
        TMainTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        TMainTree.setToolTipText("Double click a name to see the details or right clic to view options.");
        TMainTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                TMainTreeMouseReleased(evt);
            }
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TMainTreeMouseClicked(evt);
            }
        });
        TMainTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                TMainTreeValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(TMainTree);

        jSplitPane1.setLeftComponent(jScrollPane1);

        jScrollPane2.setBorder(null);
        jScrollPane2.setViewportView(TPMainPane);

        jSplitPane1.setRightComponent(jScrollPane2);

        jLabel1.setText("Search:");

        TFSearch.setText("Enter your search here...");
        TFSearch.setToolTipText("Enter your search words and press enter to search.");
        TFSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TFSearchActionPerformed(evt);
            }
        });
        TFSearch.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                TFSearchFocusGained(evt);
            }
        });

        CBSearch.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<Search by>", "Veterinarian name", "Pet name", "Owner name", "SSN", "Any name" }));
        CBSearch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                CBSearchKeyPressed(evt);
            }
        });

        MActionsMenu.setMnemonic('a');
        MActionsMenu.setText("Actions");

        MIRegisterOwner.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        MIRegisterOwner.setMnemonic('o');
        MIRegisterOwner.setText("Register Owner");
        MIRegisterOwner.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIRegisterOwnerActionPerformed(evt);
            }
        });
        MActionsMenu.add(MIRegisterOwner);

        MIRegisterPet.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        MIRegisterPet.setMnemonic('s');
        MIRegisterPet.setText("Register Pet");
        MIRegisterPet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIRegisterPetActionPerformed(evt);
            }
        });
        MActionsMenu.add(MIRegisterPet);

        MIRegisterVet.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
        MIRegisterVet.setMnemonic('a');
        MIRegisterVet.setText("Register Veterinarian");
        MIRegisterVet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIRegisterVetActionPerformed(evt);
            }
        });
        MActionsMenu.add(MIRegisterVet);

        MIExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        MIExit.setMnemonic('x');
        MIExit.setText("Exit");
        MIExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIExitActionPerformed(evt);
            }
        });
        MActionsMenu.add(MIExit);

        menuBar.add(MActionsMenu);

        MEditMenu.setMnemonic('e');
        MEditMenu.setText("Edit");

        MIEditSelected.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        MIEditSelected.setText("Edit selected...");
        MIEditSelected.setEnabled(false);
        MIEditSelected.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIEditSelectedActionPerformed(evt);
            }
        });
        MEditMenu.add(MIEditSelected);

        menuBar.add(MEditMenu);

        MTabsMenu.setMnemonic('t');
        MTabsMenu.setText("Tabs");

        MICloseCurrentTab.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        MICloseCurrentTab.setMnemonic('t');
        MICloseCurrentTab.setText("Close Current Tab");
        MICloseCurrentTab.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MICloseCurrentTabActionPerformed(evt);
            }
        });
        MTabsMenu.add(MICloseCurrentTab);

        menuBar.add(MTabsMenu);

        MHelpMenu.setMnemonic('h');
        MHelpMenu.setText("Help");

        MIAbout.setMnemonic('a');
        MIAbout.setText("About");
        MIAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIAboutActionPerformed(evt);
            }
        });
        MHelpMenu.add(MIAbout);

        menuBar.add(MHelpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TFSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CBSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(TFSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CBSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void MIExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIExitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_MIExitActionPerformed

    private void TMainTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TMainTreeMouseClicked
        TreePath pathForLocation = TMainTree.getPathForLocation(evt.getX(), evt.getY());
        if (pathForLocation != null) {
            DefaultMutableTreeNode clickedNode = (DefaultMutableTreeNode) pathForLocation.getLastPathComponent();
            if (!showPopup(clickedNode, evt)) {
                if (evt.getClickCount() == 2) {
                    Object userObject = clickedNode.getUserObject();
                    displayEntity(userObject);
                }
            }
        }  
    }//GEN-LAST:event_TMainTreeMouseClicked

    private void MIRegisterOwnerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIRegisterOwnerActionPerformed
        TPMainPane.add("Register Owner", new POwnerRegistration());
    }//GEN-LAST:event_MIRegisterOwnerActionPerformed

    private void MICloseCurrentTabActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MICloseCurrentTabActionPerformed
        closeCurrentTab();
    }//GEN-LAST:event_MICloseCurrentTabActionPerformed

    private void TFSearchFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_TFSearchFocusGained
        TFSearch.selectAll();
    }//GEN-LAST:event_TFSearchFocusGained

    private void MIRegisterVetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIRegisterVetActionPerformed
        TPMainPane.add("Register Veterinarian", new PVetRegistration());
    }//GEN-LAST:event_MIRegisterVetActionPerformed

    private void MIRegisterPetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIRegisterPetActionPerformed
        TPMainPane.add("Register Pet", new PPetRegistration());
    }//GEN-LAST:event_MIRegisterPetActionPerformed

    private void MIAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIAboutActionPerformed
        // TODO
    }//GEN-LAST:event_MIAboutActionPerformed

    private void TMainTreeMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TMainTreeMouseReleased
        TreePath pathForLocation = TMainTree.getPathForLocation(evt.getX(), evt.getY());
        if (pathForLocation != null) {
            DefaultMutableTreeNode clickedNode = (DefaultMutableTreeNode) pathForLocation.getLastPathComponent();
            showPopup(clickedNode, evt);
        }
    }//GEN-LAST:event_TMainTreeMouseReleased

    private void MIEditEntityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIEditEntityActionPerformed
        editSelectedEntity();
    }//GEN-LAST:event_MIEditEntityActionPerformed

    private void TMainTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_TMainTreeValueChanged
        TreePath path = evt.getPath();
        if (path != null) {
            DefaultMutableTreeNode lastNode = (DefaultMutableTreeNode) path.getLastPathComponent();
            if (lastNode.getUserObject() instanceof String) {
                MIEditSelected.setEnabled(false);
            } else {
                MIEditSelected.setEnabled(true);
            }
        } else {
            MIEditSelected.setEnabled(false);
        }
    }//GEN-LAST:event_TMainTreeValueChanged

    private void MIEditSelectedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIEditSelectedActionPerformed
        editSelectedEntity();
    }//GEN-LAST:event_MIEditSelectedActionPerformed

    private void MIDeleteEntityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIDeleteEntityActionPerformed
        deleteEntity(getSelectedEntity());
    }//GEN-LAST:event_MIDeleteEntityActionPerformed

    private void MIViewEntityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIViewEntityActionPerformed
        displayEntity(getSelectedEntity());
    }//GEN-LAST:event_MIViewEntityActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        for (int i = 0; i < TPMainPane.getTabCount(); i++) {
            Component component = TPMainPane.getComponentAt(i);
            if (component instanceof PVetDisplay) {
                PVetDisplay pvd = (PVetDisplay) component;
                pvd.save();
            }
        }
    }//GEN-LAST:event_formWindowClosing

    private void TFSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TFSearchActionPerformed
        search();
    }//GEN-LAST:event_TFSearchActionPerformed

    private void CBSearchKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CBSearchKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            search();
        }
    }//GEN-LAST:event_CBSearchKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox CBSearch;
    private javax.swing.JMenu MActionsMenu;
    private javax.swing.JMenu MEditMenu;
    private javax.swing.JMenu MHelpMenu;
    private javax.swing.JMenuItem MIAbout;
    private javax.swing.JMenuItem MICloseCurrentTab;
    private javax.swing.JMenuItem MIDeleteEntity;
    private javax.swing.JMenuItem MIEditEntity;
    private javax.swing.JMenuItem MIEditSelected;
    private javax.swing.JMenuItem MIExit;
    private javax.swing.JMenuItem MIRegisterOwner;
    private javax.swing.JMenuItem MIRegisterPet;
    private javax.swing.JMenuItem MIRegisterVet;
    private javax.swing.JMenuItem MIViewEntity;
    private javax.swing.JMenu MTabsMenu;
    private javax.swing.JPopupMenu PMTreePopupMenu;
    private javax.swing.JTextField TFSearch;
    private javax.swing.JTree TMainTree;
    private javax.swing.JTabbedPane TPMainPane;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JMenuBar menuBar;
    // End of variables declaration//GEN-END:variables

}
